package com.cmsz.shuang.booter.service;

import java.util.List;
import java.util.Random;

import javax.annotation.PostConstruct;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


@Service
public class CacheDemo {

	/**
	 * 缓存的key
	 */
	public static final String THING_ALL_KEY = "\"thing_all\"";
	/**
	 * value属性表示使用哪个缓存策略，缓存策略在ehcache.xml
	 */
	public static final String DEMO_CACHE_NAME = "demo";

	@CacheEvict(value = DEMO_CACHE_NAME, key = THING_ALL_KEY)
	public void create(Long thing) {
		Long id = getNextId();
	}

	private Long getNextId() {
		Random r = new Random();
		return r.nextLong();
	}

	// @Cacheable(value = DEMO_CACHE_NAME,key = "#thing.getId()+'thing'")
	@Cacheable(value = DEMO_CACHE_NAME)
	public Long findById(long id) {
		System.err.println("没有走缓存！" + id);
		return getNextId();
	}

	@Cacheable(value = DEMO_CACHE_NAME, key = THING_ALL_KEY)
	public List<Long> findAll() {
		return null;
	}

	@CachePut(value = DEMO_CACHE_NAME, key = "#thing.getId()+'thing'")
	@CacheEvict(value = DEMO_CACHE_NAME, key = THING_ALL_KEY)
	public Long update(Long thing) {
		System.out.println(thing);
		// data.put (thing.getId (), thing);
		return thing;
	}

	@CacheEvict(value = DEMO_CACHE_NAME)
	public void delete(Long id) {
		System.out.println("delete " + id);
	}
	
	@PostConstruct
	public void printt()
	{
		long l;
		l=this.findById(100L);
		System.out.println("l="+ l);
		this.findById(100L);
		
	}

}
